<?php

require_once( sfConfig::get('sf_plugins_dir').'/sfThumbnailPlugin/lib/sfGDAdapter.class.php');
require_once( sfConfig::get('sf_plugins_dir').'/sfThumbnailPlugin/lib/sfThumbnail.class.php');

/**
 * LodgingPhoto form.
 *
 * @package    SchelkinoBiz
 * @subpackage form
 * @author     Delight
 */
class LodgingPhotoForm extends BaseLodgingPhotoForm
{
    public function configure()
    {
        $lodging_dir = sfConfig::get('sf_upload_dir').DIRECTORY_SEPARATOR.sfConfig::get('app_photos_dir');
        $dirs        = sfConfig::get('app_photos_dirs');

        $file_dir    = $lodging_dir.DIRECTORY_SEPARATOR.$dirs['mini'].DIRECTORY_SEPARATOR;
        $file_src    = sfConfig::get('app_photos_path');

        if ( !$this->isNew() && is_readable( $file_dir.$this->getObject()->getLodgingPhoto() ) )
            $this->widgetSchema['lodging_photo'] = new sfWidgetFormInputFileExist(array(
                'is_image' => true,
                'file_src' => $file_src['mini'].$this->getObject()->getLodgingPhoto(),
            ));
        else
            $this->widgetSchema['lodging_photo'] = new sfWidgetFormInputFile();

        $sfValidatorFileOptions = array(
            'path'       => sfConfig::get('sf_upload_dir').DIRECTORY_SEPARATOR.sfConfig::get('app_photos_dir').DIRECTORY_SEPARATOR.sfConfig::get('app_photos_original'),
            'mime_types' => 'web_images',
            'required' => false
        );

        $this->validatorSchema['lodging_photo'] = new sfValidatorFile( $sfValidatorFileOptions );

        $this->validatorSchema->setOption('allow_extra_fields', true);

        $this->embedI18n( sfConfig::get('app_default_cultures') );
    }

    protected function saveFile($field, $filename = null, sfValidatedFile $file = null)
    {
        $filename = parent::saveFile($field, $filename, $file);

        $lodging_dir = sfConfig::get('sf_upload_dir').DIRECTORY_SEPARATOR.sfConfig::get('app_photos_dir');
        $dirs = sfConfig::get('app_photos_dirs');

        foreach ( sfConfig::get('app_photos_sizes') as $k => $size )
        {
            $path_to_file = $lodging_dir.DIRECTORY_SEPARATOR.$dirs[$k].DIRECTORY_SEPARATOR;

            $new_size = explode( "x", $size, 2 );
            $thumbnail = new sfThumbnail( $new_size[0], $new_size[1] );
            $thumbnail->loadFile($file->getTempName());
            $thumbnail->save( $path_to_file.$filename, $file->getType() );
            if ( !$this->isNew() )
                unlink( $path_to_file.$this->getObject()->getLodgingPhoto() );
        }

        return $filename;
    }
}
